import Viewer from 'viewerjs';
import 'viewerjs/dist/viewer.css';

export function openViewer(el, index = 0, option = {}) {
  const className = 'viewerjs-' + Date.now().toString(36);
  let viewer = new Viewer(el, {
    movable: true,
    initialViewIndex: index,
    className: className,
    hide() {
      if (typeof option.hide === 'function') {
        option.hide(viewer);
      }
      if (viewer) {
        viewer.destroy();
        viewer = null;
      }
      option = null;
    },
  });
}

export function viewImages(img, index = 0) {
  /*
   * img: 图片地址的数组
   * index: 默认预览图片索引
   * */
  if (!Array.isArray(img)) {
    img = [img];
  }
  img = img.filter((item) => Boolean(item));
  if (!img.length) return;
  let div = document.createElement('div');
  div.style.cssText = 'position: absolute;top: -999999px;left: -999999px;';
  document.body.appendChild(div);
  img.forEach((url) => {
    const img = document.createElement('img');
    img.src = url;
    div.appendChild(img);
  });
  openViewer(div, index, {
    hide: () => {
      if (div && div.parentElement) {
        div.parentElement.removeChild(div);
        div = null;
      }
    },
  });
  if (div.firstElementChild) {
    div.firstElementChild.click();
  }
}
